from django import http
from django.shortcuts import render, redirect
from django_redis import get_redis_connection
import re
import random

from django.views import View

from meiduo_mall.libs.captcha.captcha import captcha
from meiduo_mall.libs.yuntongxun.sms import CCP

#获取图片验证码
from meiduo_mall.utils.constants import REDIS_IMAGE_CODE_EXPIRES, REDIS_CODE_MAX, REDIS_SMS_CODE_EXPIRES, \
    REDIS_SEND_FLOG_EXPIRES
from meiduo_mall.utils.response_code import RET


class ImagecodeView(View):
    def get(self, request, uuid):
        # 1,获取图片验证码
        _, text, image = captcha.generate_captcha()

        # 2,保存验证码到redis库
        redis_conn = get_redis_connection('image_code')
        redis_conn.set('image_code_%s' % uuid, text, REDIS_IMAGE_CODE_EXPIRES)

        # 返回图形验证码
        return http.HttpResponse(image, content_type='image.jpg')

#获取短信验证码
class SmscodeView(View):
    def get(self, request, mobile):
        # 1,获取参数
        image_code = request.GET.get('image_code')
        print(image_code)
        image_code_id = request.GET.get('image_code_id')

        # 获取短信发送时间，避免重复发送
        redis_conn = get_redis_connection('image_code')
        pipeline = redis_conn.pipeline()
        send_flog = redis_conn.get('send_flog_%s' % mobile)
        if send_flog:
            return http.HttpResponseForbidden({'code': RET.DBERR, 'errmsg': '短信重发送'})

        # 2,校验参数
        # 为空校验
        if not all(['image_code', 'mobile']):
            return http.HttpResponseForbidden({'code': RET.DATAERR, 'errmsg': '参数不全'})

        # 手机号格式错误
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.HttpResponseForbidden({'code': RET.DATAERR, 'errmsg': '手机号格式错误'})

        # 校验图形验证码
        redis_image_code = redis_conn.get('image_code_%s' % image_code_id).decode()
        print(redis_image_code)
        # 判断验证码是否过期
        if not redis_image_code:
            return http.HttpResponseForbidden({'code': RET.NODATA, 'errmsg': '图形验证码过期'})
        #校验图形验证码
        if image_code.upper() != redis_image_code.upper():
            return http.HttpResponseForbidden({'code': RET.DATAERR, 'errmsg': '图形验证码错误'})

        # 发送短信，数据入库
        sms_code = '%06d' % random.randint(0, REDIS_CODE_MAX)
        print('sms_code = %s' % sms_code)

        # 使用celery发送短信
        # from celery_tasks.sms.tasks import send_message
        # send_message.delay(mobile, sms_code)

        # 保存短信验证码到redis库
        pipeline.set('sms_code_%s' % mobile, sms_code, REDIS_SMS_CODE_EXPIRES)

        # 设置标记，防止一分钟内多次发送信息
        pipeline.set('send_flog_%s' % mobile, 1, REDIS_SEND_FLOG_EXPIRES)

        # 提交pipeline
        pipeline.execute()

        return http.JsonResponse({'code':RET.OK})
